Strings to Arrays and Back II

This applet recapitulates Strings to Arrays and Back, using JavaScript 1.2 functions to reduce the amount of code you have to write. Just like in the other recipe:

String


Discussion

What follows shows how the code size changes when you use the native functions. The left side is the "old" code; the right side is the "new" code using native functionality.

// String to Array
function stringArray(aString)
{
    var i = 0
    var idx = 0
    var s = ""+aString
    
    if (s == "")
    {
        this.length = 0
        return this
    }
    
    // search for the colon to create each array item
    while ((idx = s.indexOf(':')) != -1)
    {
        this[i] = s.substring(0, idx)
        s = s.substring(idx+1,s.length)
        i++
    }
    
    // create final array item
    this[i]=s
    this.length = i+1
    
    return this
}
// String to Array
function stringArray(aString)
{
    return aString.split(':');
}
// Array to String
function arrayString(anArray, len)
{
    var s = ""
    
    for (var i = 0; i < (len - 1); i++)
        s += anArray[i]+":"
    if (len > 0)
        s += anArray[len - 1]
    return s
}
// Array to String
function arrayString(anArray, len)
{
    return anArray.join(':');
}
Copyright ©1998 by Charles River Media, All Rights Reserved